@{
    ViewData["Title"] = "修改外协入库单";
    Layout = null;
}

<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/layui/layui.js"></script>

<style>
    body {
        padding: 20px;
    }
    .layui-form-label {
        width: 120px;
    }
    .layui-input-block {
        margin-left: 150px;
    }
</style>

<form class="layui-form" lay-filter="outsourcingEditForm">
    <input type="hidden" name="id" id="id">
    <div class="layui-form-item">
        <label class="layui-form-label">
            <span style="color:red;">*</span> 入库单编号
        </label>
        <div class="layui-input-block">
            <input type="text" name="inboundCode" placeholder="请输入入库单编号" class="layui-input" required lay-verify="required" readonly>
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label">
            <span style="color:red;">*</span> 入库单名称
        </label>
        <div class="layui-input-block">
            <input type="text" name="inboundName" placeholder="请输入入库单名称" class="layui-input" required lay-verify="required">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label">
            <span style="color:red;">*</span> 入库日期
        </label>
        <div class="layui-input-block">
            <input type="text" name="inboundDate" id="inboundDate" placeholder="请选择入库日期" class="layui-input" required lay-verify="required">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label">
            <span style="color:red;">*</span> 外协工单
        </label>
        <div class="layui-input-block">
            <input type="text" name="workOrders" placeholder="请输入外协工单" class="layui-input" required lay-verify="required">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label">
            单据状态
        </label>
        <div class="layui-input-block">
            <input type="text" name="documentStatus" class="layui-input" readonly>
            <input type="hidden" name="documentStatusValue">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label">
            采购订单号
        </label>
        <div class="layui-input-block">
            <input type="text" name="purchaseOrderNumber" placeholder="请输入采购订单号" class="layui-input">
        </div>
    </div>
    
    <div class="layui-form-item">
        <label class="layui-form-label">
            <span style="color:red;">*</span> 供应商
        </label>
        <div class="layui-input-block">
            <select name="vendor" lay-filter="vendorFilter" required lay-verify="required">
                <option value="">请选择</option>
                <option value="上海机械制造有限公司">上海机械制造有限公司</option>
                <option value="北京精密零件厂">北京精密零件厂</option>
                <option value="深圳电子科技有限公司">深圳电子科技有限公司</option>
            </select>
            <input type="hidden" name="vendorCode" id="vendorCode">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">
            备注
        </label>
        <div class="layui-input-block">
            <textarea name="remark" placeholder="请输入备注信息" class="layui-textarea"></textarea>
        </div>
    </div>
    
    <!-- 分割线 -->
    <fieldset class="layui-elem-field layui-field-title">
        <legend>物料信息</legend>
    </fieldset>
    
    <!-- 物料表格 -->
    <div class="layui-form-item">
        <div class="layui-input-block" style="margin-left: 0;">
            <table id="materialTable" lay-filter="materialTable"></table>
        </div>
    </div>
    
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn" lay-submit lay-filter="outsourcingEditSubmit">保存</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
            <button type="button" class="layui-btn layui-btn-normal" id="executeInboundBtn" style="display:none;">执行入库</button>
        </div>
    </div>
</form>

<script>
    layui.use(['form', 'layer', 'laydate', 'table'], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var table = layui.table;
        var $ = layui.$;
        
        // 获取URL参数
        function getQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
        
        // 日期选择器
        laydate.render({
            elem: '#inboundDate'
        });
        
        // 监听供应商选择事件
        form.on('select(vendorFilter)', function(data) {
            var code = $(data.elem).find("option:selected").attr("data-code");
            $('#vendorCode').val(code || '');
        });
        
        // 在form表单中添加隐藏字段
        $('form.layui-form').append('<input type="hidden" name="materielCode" value="">');
        
        // 表单提交
        form.on('submit(outsourcingEditSubmit)', function(data) {
            // 确保将documentStatusValue的值传递给后端
            data.field.documentStatus = data.field.documentStatusValue;
            
            // 获取物料数据
            var materialData = table.getData('materialTable');
            
            // 构建提交数据
            var submitData = {
                ...data.field,
                materials: materialData
            };
            
            console.log('提交的数据:', submitData); // 添加日志便于调试
            
            $.ajax({
                url: '/Outsourcing/UpdateOutsourcing',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(submitData),
                success: function(res) {
                    if (res.success) {
                        layer.msg('修改成功', {icon: 1, time: 1000}, function() {
                            // 关闭当前弹出层
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        });
                    } else {
                        layer.msg('修改失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('服务器错误，请稍后再试', {icon: 2});
                }
            });
            return false;
        });
        
        // 取消按钮
        $('#cancelBtn').on('click', function() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        });
        
        // 加载仓库下拉选择
        function loadWarehouses() {
            var warehouses = [
                { id: '原料仓库', warehouseName: '原料仓库' },
                { id: '成品仓库', warehouseName: '成品仓库' },
                { id: '半成品仓库', warehouseName: '半成品仓库' }
            ];
            
            var html = '<option value="">请选择</option>';
            $.each(warehouses, function(i, item) {
                html += '<option value="' + item.id + '">' + item.warehouseName + '</option>';
            });
            $('select[name="warehouseId"]').html(html);
            form.render('select');
        }
        
        // 加载供应商下拉选择
        function loadVendors() {
            var vendors = [
                { vendorCode: '上海机械制造有限公司', vendorName: '上海机械制造有限公司' },
                { vendorCode: '北京精密零件厂', vendorName: '北京精密零件厂' },
                { vendorCode: '深圳电子科技有限公司', vendorName: '深圳电子科技有限公司' }
            ];
            
            var html = '<option value="">请选择</option>';
            $.each(vendors, function(i, item) {
                html += '<option value="' + item.vendorName + '" data-code="' + item.vendorCode + '">' + item.vendorName + '</option>';
            });
            $('select[name="vendor"]').html(html);
            form.render('select');
        }
        
        // 页面初始化时隐藏按钮
        $('#executeInboundBtn').hide();
        
        // 根据ID获取外协入库单数据
        function loadOutsourcingById(id) {
            $.ajax({
                url: '/Outsourcing/GetByIdOutsourcing',
                type: 'GET',
                data: { id: id },
                success: function(res) {
                    if (res.success && res.data) {
                        // 处理日期格式
                        if (res.data.inboundDate) {
                            if (typeof res.data.inboundDate === 'string' && res.data.inboundDate.indexOf('T') > -1) {
                                res.data.inboundDate = res.data.inboundDate.split('T')[0];
                            } else if (typeof res.data.inboundDate === 'number') {
                                res.data.inboundDate = layui.util.toDateString(new Date(res.data.inboundDate), 'yyyy-MM-dd');
                            }
                        }
                        
                        // 设置单据状态的文本显示
                        var statusText = '';
                        switch(parseInt(res.data.documentStatus)) {
                            case 1:
                                statusText = '草稿';
                                break;
                            case 2:
                                statusText = '待入库';
                                break;
                            case 3:
                                statusText = '已入库';
                                break;
                            default:
                                statusText = '未知状态';
                        }
                        res.data.documentStatusValue = res.data.documentStatus;
                        res.data.documentStatus = statusText;
                        
                        // 存储MaterielCode值，用于后续选中对应行
                        var selectedMaterielCode = res.data.materielCode || '';
                        console.log('数据库存储的物料编码:', selectedMaterielCode);
                        
                        // 设置表单数据
                        form.val('outsourcingEditForm', res.data);
                        
                        console.log("当前单据状态:", res.data.documentStatusValue); // 添加日志，查看状态值
                        
                        // 控制执行入库按钮显示和表单权限
                        var docStatus = parseInt(res.data.documentStatusValue);
                        
                        if (docStatus === 1) {
                            // 草稿状态(1)，可编辑，隐藏执行入库按钮
                            $('#executeInboundBtn').hide();
                            console.log("草稿状态，可编辑，隐藏执行入库按钮");
                        } else if (docStatus === 2) {
                            // 待入库状态(2)，可编辑，显示执行入库按钮
                            $('#executeInboundBtn').show();
                            console.log("待入库状态，可编辑，显示执行入库按钮");
                        } else if (docStatus === 3) {
                            // 已入库状态(3)，禁用表单，隐藏执行入库按钮
                            $('input,select,textarea').prop('disabled', true).addClass('layui-disabled');
                            $('.layui-btn[lay-filter="outsourcingEditSubmit"]').prop('disabled', true).addClass('layui-btn-disabled');
                            $('#executeInboundBtn').hide();
                            console.log("已入库状态，禁用表单，隐藏执行入库按钮");
                        } else {
                            // 其他状态，默认隐藏执行入库按钮
                            $('#executeInboundBtn').hide();
                            console.log("未知状态，隐藏执行入库按钮");
                        }
                        
                        form.render();
                    } else {
                        layer.msg('获取数据失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('获取数据失败，请稍后再试', {icon: 2});
                }
            });
        }
        
        // 初始化物料表格
        var materialTable = table.render({
            elem: '#materialTable',
            cols: [[
                {type: 'radio', fixed: 'left'},  // 添加单选按钮作为第一列
                {field: 'materialCode', title: '物料编码', width: 130},
                {field: 'materialName', title: '物料名称', width: 150},
                {field: 'specification', title: '规格型号', width: 120},
                {field: 'unit', title: '单位', width: 80},
                {field: 'quantity', title: '数量', width: 100},
                {field: 'batchNo', title: '批次号', width: 120},
                {field: 'remark', title: '备注', width: 150}
            ]],
            height: 300
        });
        
        // 监听物料单选按钮事件
        table.on('radio(materialTable)', function(obj){
            var materialCode = obj.data.materialCode;
            console.log('选中物料编号:', materialCode);
            // 将选中的物料编码赋值给表单字段
            $('input[name="materielCode"]').val(materialCode);
        });
        
        // 加载物料数据
        function loadMaterialData(callback) {
            $.ajax({
                url: '/Outsourcing/GetListAsync',
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json',
                success: function(res) {
                    console.log('API返回数据:', res);
                    if (res && res.data) {
                        table.reload('materialTable', {
                            data: res.data
                        });
                    } else if (res) {
                        table.reload('materialTable', {
                            data: res
                        });
                    } else {
                        console.log('API返回数据为空');
                    }
                    // 执行回调
                    if (typeof callback === 'function') {
                        callback();
                    }
                },
                error: function(xhr) {
                    console.error('API错误:', xhr.status, xhr.responseText);
                    var mockData = [
                        {materialCode: 'M001', materialName: '钢板A', specification: '304不锈钢 2mm', unit: '张', quantity: 10, batchNo: 'B20240615001', remark: ''},
                        {materialCode: 'M003', materialName: '电机', specification: '220V 1.5KW', unit: '台', quantity: 2, batchNo: 'B20240615002', remark: ''}
                    ];
                    table.reload('materialTable', {
                        data: mockData
                    });
                    // 执行回调
                    if (typeof callback === 'function') {
                        callback();
                    }
                }
            });
        }
        
        // 页面初始化
        loadVendors();
        loadWarehouses();
        
        // 获取ID参数并加载数据
        var id = getQueryString('id');
        if (id) {
            loadOutsourcingById(id);
            // 先加载外协入库单数据，再加载物料数据
            setTimeout(function() {
                loadMaterialData(function() {
                    // 物料数据加载完成后，根据materielCode选中对应行
                    var materielCode = $('input[name="materielCode"]').val();
                    if (materielCode) {
                        console.log('尝试选中物料编码:', materielCode);
                        // 获取表格数据
                        var tableData = table.getData('materialTable');
                        // 查找对应编码的行索引
                        var foundIndex = -1;
                        for (var i = 0; i < tableData.length; i++) {
                            if (tableData[i].materialCode === materielCode) {
                                foundIndex = i;
                                break;
                            }
                        }
                        if (foundIndex >= 0) {
                            // 选中对应行
                            table.setRowChecked('materialTable', {
                                index: foundIndex,
                                type: 'radio'
                            });
                            console.log('已选中物料行，索引:', foundIndex);
                        } else {
                            console.log('未找到匹配的物料行');
                        }
                    }
                });
            }, 500);
        } else {
            layer.msg('未找到要编辑的记录', {icon: 2});
        }

        // 执行入库按钮点击事件
        $('#executeInboundBtn').on('click', function() {
            var id = $('#id').val();
            if (!id) {
                layer.msg('未找到有效记录ID', {icon: 2});
                return;
            }
            
            layer.confirm('确定要执行入库操作吗？此操作将变更状态为已入库，不可逆转。', function(index) {
                $.ajax({
                    url: '/Outsourcing/ExecuteInbound',
                    type: 'POST',
                    data: { id: id },
                    success: function(res) {
                        if (res.success) {
                            layer.msg('执行入库成功', {icon: 1}, function() {
                                // 刷新页面或返回列表
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            });
                        } else {
                            layer.msg('执行入库失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('服务器错误，请稍后再试', {icon: 2});
                    }
                });
                
                layer.close(index);
            });
        });
    });
</script> 